import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/pages/specialtopic/entity/special_topic_commodity_entity.dart';
import 'package:get/get.dart';

import '../../../components/base/base_ctr.dart';
import '../../../utils/Tools.dart';
import '../../../utils/wechat_mini_program_share_utils.dart';

class SpecialTopicCtr extends BaseController {
  SpecialTopicCommodityData? data; // 使用可空类型
  SpecialTopicCommodityDataGoodsList? goodsList; // 使用可空类型
  List list = [];
  bool hasNextPage = false;

  @override
  void onInit() {
    super.onInit();
    onPageRefresh();
  }

  ///监听页面下拉刷新
  @override
  void onPageRefresh() {
    super.onPageRefresh();
    getSpecialTopic(true);
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  ///监听页面上拉加载
  @override
  void onPageLoading() {
    if (hasNextPage == true) {
      super.onPageLoading();
      getSpecialTopic(false);
      baseRefreshCtr.loadComplete();
    }
  }

  Future getSpecialTopic(bool isRefresh) async {
    var id = Get.arguments['id'];
    Tools.showLoading();
    int current = isRefresh ? 1 : pageNum + 1;
    return Network.getSpecialTopic(current, pageSize, id.toString()).then((value) {
      pageNum = current;
      data = SpecialTopicCommodityData.fromJson(value);

      // 处理 goodsList，如果 data 或 goodsList 为空则赋默认值
      if (data?.goodsList != null) {
        goodsList = data!.goodsList!;
      } else {
        goodsList = null;
      }

      // 根据是否刷新操作来处理列表
      if (isRefresh) {
        if (goodsList?.list != null) {
          list = goodsList!.list!;
        } else {
          list = [];
        }
      } else {
        if (goodsList?.list != null) {
          list.addAll(goodsList!.list!);
        }
      }

      // 判断是否有下一页数据
      if (data?.goodsList != null) {
        hasNextPage = data!.goodsList!.hasNextPage ?? false;
      } else {
        hasNextPage = false;
      }

      Tools.hideLoading();
      update(); // 更新UI
    }).catchError((onError) {
      Tools.hideLoading();
      Tools.showToast('数据请求失败');
    });
  }

  // 分享
  void sharePage() {
    var id = Get.arguments['id'];
    WeChatShareUtils.shareMiniProgram(id.toString(), 'assets/images/login_logo.png', WeChatShareType.topicGallery);
  }
}
